<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			#ad {
				position: absolute;
			}
		</style>
	</head>
	<body onload="startInterVal()">
		<img id="ad" width="200" height="200"
			onmouseout="startInterVal()"
			onmouseover="clearSetInterVal()"
			src="https://www.runoob.com/images/pulpit.jpg"/>
		<script type="text/javascript">
			let x = 0;
			let y = 0;
			var adImage = document.getElementById("ad");
			const width = adImage.clientWidth;		//获取图片的宽度
			const height = adImage.clientHeight;	//获取图片的高度
			
			const offsetWidth = window.innerWidth - width; //最大可移动的宽度
			const offsetHeight = window.innerHeight - height; //最大可移动高度
			const speed = 2
			let dx = speed;
			let dy = speed;
			
			function move(){
				x += dx;
				y += dy;
				if(x >= offsetWidth || x <=0){
					dx = -dx
				}
				if(y >= offsetHeight || y <=0){
					dy = -dy
				}
				adImage.style.left = `${x}px`;
				adImage.style.top = `${y}px`;
			}
			var timer = null
			
			function startInterVal(){		//启动定时器
				timer = setInterval(move,50)		//定时器,  1000代表的是1秒钟
			}
			
			function clearSetInterVal(){
				window.clearInterval(timer)	//关闭定时器
			}
			
		</script>
	</body>
</html>